package cn.tedu.boot.ers.service.impl;

import cn.tedu.boot.ers.entity.User;
import cn.tedu.boot.ers.exception.ServiceException;
import cn.tedu.boot.ers.mapper.UserMapper;
import cn.tedu.boot.ers.pojo.dto.*;
import cn.tedu.boot.ers.pojo.vo.UserDetailsVO;
import cn.tedu.boot.ers.service.IUserService;
import cn.tedu.boot.ers.util.PasswordUtils;
import cn.tedu.boot.ers.web.State;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    UserMapper mapper;

    @Override
    public void addNew(UserDTO userDTO) {
        //获取客户端的用户名
        String username = userDTO.getUsername();
        //查询数据库用户名getByUsername（）
        //根据用户名判断是否不为null
        //1.是 则抛出异常用户名已存在new UserDuplicateException（”“）
        if (mapper.getByName(username) != null) {
            throw new ServiceException(State.ERR_BAD_REQUEST, "用户名:" + username + "已经存在");
        }
        //2.否 则继续执行
        //new User
        User user = new User();
        //BeanUtils.copyProperties()
        //加密处理
        String password = PasswordUtils.encodePassword(userDTO.getPassword());
        userDTO.setPassword(password);
        BeanUtils.copyProperties(userDTO, user);
        //补全
        user.setHeadUrl("url");
        user.setLevel("0");
        user.setMoney(BigDecimal.valueOf(0.00));
        user.setBirthday(LocalDate.now());
        //调用UserMapper.insert 并查看返回是否为1不为1抛出异常
        int rows = mapper.insert(user);
        if (rows != 1) {
            throw new ServiceException(State.ERR, "服务器开了小差，稍后再试");
        }
        //用户添加成功
    }

    @Override
    public void updatePassword(UserUpdatePasswordDTO upDTO) {
        //获取客户传递的电话查询数据库是否存在该用户若不存在则抛出异常
        if (mapper.getByTel(upDTO.getTel()) == null) {
            throw new ServiceException(State.ERR_BAD_REQUEST, "该用户不存在");
        }
        //根据电话查询的数据库密码和用户输入的密码对比 如果不一样 抛出异常
        boolean matches = PasswordUtils.matches(
                upDTO.getRawPassword(),
                mapper.getByTel(upDTO.getTel()).getPassword());
        if (!matches) {
            throw new ServiceException(State.ERR_BAD_REQUEST, "输入密码错误");
        }
//        if (!mapper.getByTel(upDTO.getTel()).getPassword().equals(upDTO.getRawPassword())){
//            throw new ServiceException(State.ERR_BAD_REQUEST,"输入密码错误");
//        }

        //如果密码匹配则继续执行 可直接修改密码
//        int i = mapper.updatePassword(upDTO.getRawPassword(), upDTO.getNewPassword());
        upDTO.setNewPassword(PasswordUtils.encodePassword(upDTO.getNewPassword()));
        int i = mapper.updatePassword(upDTO);
        if (i != 1) {
            throw new ServiceException(State.ERR, "服务器开小差稍后再试");
        }
    }

    @Override
    public void updateInfo(UserUpdateInfoDTO userUpdateInfoDTO) {
        //判断用户名是否存在 否则抛出异常
        if (mapper.getByName(userUpdateInfoDTO.getUsername()) == null) {
            throw new ServiceException(State.ERR_BAD_REQUEST, "该用户不存在");
        }
        int i = mapper.updateBaseInfo(userUpdateInfoDTO.getTel(), userUpdateInfoDTO.getGender(),
                userUpdateInfoDTO.getHeadUrl(), userUpdateInfoDTO.getUsername());
        if (i != 1) {
            throw new ServiceException(State.ERR_BAD_REQUEST, "服务器开小差稍后再试");
        }
    }

    @Override
    public void updateBalance(UserUpdateMoneyDTO userUpdateMoneyDTO) {
        //判断用户名是否存在 否则抛出异常
        if (mapper.getByName(userUpdateMoneyDTO.getUsername()) == null) {
            throw new ServiceException(State.ERR_BAD_REQUEST, "用户不存在");
        }

        int rows = mapper.updateMoney(userUpdateMoneyDTO.getUsername(), userUpdateMoneyDTO.getMoney(),
                userUpdateMoneyDTO.getLevel());
        if (rows != 1) {
            throw new ServiceException(State.ERR_BAD_REQUEST, "服务器开小差稍后再试");
        }
    }


    @Override
    public UserDetailsVO getUserByUsername(String username) {
        //判断用户名是否存在
        UserDetailsVO result = mapper.getByName(username);
        //不存在则抛出错误 用户名不存在
        if (result == null) {
            throw new ServiceException(State.ERR_BAD_REQUEST, "请求错误用户名不存在");
        }
        return result;
    }

    @Override
    public UserDetailsVO getUserByTel(String tel) {
        //根据电话查询电话是否存在
        UserDetailsVO result = mapper.getByTel(tel);
        //不存在则抛出 电话
        if (result == null) {
            throw new ServiceException(State.ERR_BAD_REQUEST, "请求错误电话不存在");
        }
        return result;
    }

    @Override
    public UserDetailsVO UserLogin(UserLoginDTO userloginDTO, HttpSession session) {
        //根据客户端传递的用户名信息查询用户名是否存在
        UserDetailsVO result = mapper.getByName(userloginDTO.getUsername());
        //不存在则抛出异常用户名不存在
        if (result == null) {
            throw new ServiceException(State.ERR_BAD_REQUEST, "用户名不存在");
        }
        //存在则判断客户端传递的密码是否与数据库密码匹配
        //不匹配则密码错误
        boolean passwordResult = PasswordUtils.matches(userloginDTO.getPassword(), result.getPassword());
        if (!passwordResult) {
            throw new ServiceException(State.ERR_BAD_REQUEST, "密码错误");
        }
        //匹配则表示登录成功 并把结果返回且到HttpSession保存在会话中
        session.setAttribute("user", result);
        return result;
    }

    @Override
    public List<UserDetailsVO> userList() {
        List<UserDetailsVO> list = mapper.getUserList();
        return list;
    }
}
